package com.jml.zlhq.app.ui;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONObject;

import com.edmodo.cropper.CropImageView;
import com.jml.zlhq.app.AppConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.ImageUtils;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.utils.StorageUtils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class PicCutActivity extends BaseActivity {  
	private CropImageView cropImageView;
	private TextView cancel;
	private TextView submit;
	private File file;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pic_cute);
		
		Intent intent= getIntent();
		String image = intent.getStringExtra("image");
		
		cancel = (TextView) findViewById(R.id.pic_cute_cancale);
		submit = (TextView) findViewById(R.id.pic_cute_submit);
		cropImageView = (CropImageView) findViewById(R.id.pic_cut_img);
		
		String name = new File(image).getName();
		File images = StorageUtils.getOwnCacheDirectory(this, AppConfig.APP_CAMERA);
		file = new File(images,name);
		try {
			ImageUtils.createImageThumbnail(this, image, file.getAbsolutePath(), 720, 100);
		} catch (IOException e) {
			e.printStackTrace();
		}
		cropImageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
		cancel.setOnClickListener(this);
		submit.setOnClickListener(this);
		
	}
	
	@Override
	public void loadData(Map<String, String> param) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void clearData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.pic_cute_cancale:
			finish();
			break;
		case R.id.pic_cute_submit:
			Bitmap bitmap = cropImageView.getCroppedImage();
			if(bitmap==null){
				UIUtil.ToastMessage(this, "裁剪出错了~", Toast.LENGTH_SHORT);
			}else{
//				RequestParams params = new RequestParams();
				try {
					ImageUtils.saveImageToSD(null,file.getAbsolutePath(), bitmap, 100);
//					params.put("file", file);
//					params.put("type", 0);
				} catch (IOException e) {
					e.printStackTrace();
				}
				final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "保存中，请稍后...", false);
				Map<String, String> map = new HashMap<String, String>();
				Map<String, File> files = new HashMap<String, File>();
				map.put("type", 0+"");
				files.put("file", file);
				HttpService.upload(URLs.FILE_UPLOAD, map, files, new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, Header[] arg1, String arg2) {
						mProDialog.dismiss();
						try {
							Log.i("======", arg2);
							JSONObject result = new JSONObject(arg2);
							if(result.getInt("status")==0){
								Intent data = new Intent();
								data.putExtra("file", file.getAbsolutePath());
								data.putExtra("fileremote", BaseTools.getFrom("data.file", result));
								setResult(Activity.RESULT_OK, data);
								finish();
							}else{
								UIUtil.ToastMessage(activity, "上传失败");
							}
						}catch(Exception e){}
						
					}
					
					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
						mProDialog.dismiss();
						UIUtil.ToastMessage(activity, "上传失败");
					}
				});
			}
//				RequestParams params = new RequestParams();
//				try {
//					final String contentType = RequestParams.APPLICATION_OCTET_STREAM;
//					params.put("type", 0);
//					params.put("file", file, contentType,"file");
//					params.setHttpEntityIsRepeatable(true);
//		            params.setUseJsonStreamer(false);
//				} catch (FileNotFoundException e) {
//					e.printStackTrace();
//				}
				/*HttpService.postByFile(activity, URLs.FILE_UPLOAD, params, new TextHttpResponseHandler(){
						@Override
						public void onSuccess(int arg0, Header[] arg1, String resultStr) {
							mProDialog.dismiss();
							try {
								if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
								JSONObject result = new JSONObject(resultStr);
								if(result.getInt("status")==0){
									Intent data = new Intent();
									data.putExtra("file", file.getAbsolutePath());
									setResult(Activity.RESULT_OK, data);
									finish();
								}else{
									UIUtil.ToastMessage(activity, "上传失败");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						
						@Override
						public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
							mProDialog.dismiss();
							UIUtil.ToastMessage(activity, "上传失败");
						}
				});//(, map, files);
					
			
				
			}*/
				/*AsyncTask<Void, Void, JSONObject> task = new AsyncTask<Void, Void, JSONObject>() {
					@Override
					protected JSONObject doInBackground(Void... arg0) {
						try {
							Map<String, String> map = new HashMap<String, String>();
							Map<String, File> files = new HashMap<String, File>();
							map.put("type", 0+"");
							files.put("file", file);
							return HttpService.upload(URLs.FILE_UPLOAD, map, files);
						} catch (Exception e) {
							e.printStackTrace();
						} 
						return null;
					}
					@Override
					protected void onPostExecute(JSONObject result) {
						mProDialog.dismiss();
						try {
							if(result!=null&&result.getInt("status")==0){
								Intent data = new Intent();
								data.putExtra("file", file.getAbsolutePath());
								setResult(Activity.RESULT_OK, data);
								finish();
//								Map<String, String> map = new HashMap<String, String>();
//								map.put("auth_token", appContext.getLoginUid());
//								map.put("value", BaseTools.getFrom("data.resouce_id", result));
//								
//								HttpService.postByText(URLs.USER_INFO_IMAGE, map, new TextHttpResponseHandler() {
//									
//									@Override
//									public void onSuccess(int arg0, Header[] arg1, String arg2) {
//										mProDialog.dismiss();
//										try {
//											Log.i("======", arg2);
//											JSONObject result = new JSONObject(arg2);
//											if(result.getInt("status")==0){
//												UIUtil.ToastMessage(activity, "上传成功");
//												WodeFragment.freshPage = true;
//												setResult(Activity.RESULT_OK);
//												finish();
//											}else{
//												UIUtil.ToastMessage(activity, "上传失败");
//											}
//										}catch(Exception e){}
//										
//									}
//									
//									@Override
//									public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//										mProDialog.dismiss();
//										UIUtil.ToastMessage(activity, "上传失败");
//									}
//								});
							}else{
								UIUtil.ToastMessage(activity, "上传失败");
							}
						} catch (JSONException e) {
							UIUtil.ToastMessage(activity, "上传失败");
							e.printStackTrace();
						}
					}
				};
				task.execute();
			}*/
//				HttpService.postByFile(this, URLs.FILE_UPLOAD, params, new TextHttpResponseHandler() {
//					
//					@Override
//					public void onSuccess(int arg0, Header[] arg1, String arg2) {
//						try {
//							JSONObject result = new JSONObject(arg2);
//							Log.i("======", arg2);
//							if(result.getInt("status")==0){
//								Map<String, String> map = new HashMap<String, String>();
//								map.put("auth_token", appContext.getLoginUid());
//								map.put("value", BaseTools.getFrom("data.resouce_id", result));
//								
//								HttpService.postByText(URLs.USER_INFO_IMAGE, map, new TextHttpResponseHandler() {
//									
//									@Override
//									public void onSuccess(int arg0, Header[] arg1, String arg2) {
//										try {
//											Log.i("======", arg2);
//											JSONObject result = new JSONObject(arg2);
//											if(result.getInt("status")==0){
//												UIUtil.ToastMessage(activity, "上传成功");
//												WodeFragment.freshPage = true;
//											}else{
//												UIUtil.ToastMessage(activity, "上传失败");
//											}
//										}catch(Exception e){}
//										
//									}
//									
//									@Override
//									public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//										UIUtil.ToastMessage(activity, "上传失败");
//									}
//								});
//							}
//						} catch (JSONException e) {
//							e.printStackTrace();
//						}
//					}
//					
//					@Override
//					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//						UIUtil.ToastMessage(activity, "上传失败");
//					}
//				});
//			}
//			if(isSubmit)return;
//			isSubmit = true;
//			Bitmap bitmap = cropImageView.getCroppedImage();
//			if(bitmap==null){
//				isSubmit = false;
//				UIHelper.ToastMessage(this, "裁剪出错了~", Toast.LENGTH_SHORT);
//			}else{
//				try {
//					ImageUtils.saveImageToSD(null,file.getAbsolutePath(), bitmap, 100);
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				SharedPreferences preferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);   
//		        final String token = preferences.getString("token", null); 
//				final Dialog  mProDialog =  UIHelper.showLoadingDialog(this, "提交中，请稍后...", false);
//		        new AsyncTask<Void, Void, List<Map<String, String>>>() {
//					@Override
//					protected List<Map<String, String>> doInBackground(Void... arg0) {
//						List<String> imagesPath = new ArrayList<String>();
//						imagesPath.add(file.getAbsolutePath());
//						return service.upload_files(imagesPath);
//					}
//
//					@Override
//					protected void onPostExecute(final List<Map<String, String>> result) {
//						new AsyncTask<Void, Void, JsonObject>() {
//							@Override
//							protected JsonObject doInBackground(Void... arg0) {
//								Map<String, Object> map = new HashMap<String, Object>();
//								map.put("auth_token", token);
//								String res = "";
//								for (Map<String, String> map2 : result) {
//									res=map2.entrySet().iterator().next().getValue();
//								}
//								map.put("value", res);
//								return service.loadPageJson(HttpType.POSTNOR, URLs.MAIN_MINE_INFOPOST_IMAGE_JSONDATURL, map, null);
//							}
//							@Override
//							protected void onPostExecute(JsonObject result) {
//								mProDialog.dismiss();
//								if(result!=null){
//									Log.i("rigister_vcode", result.toString());
//									if(DataUtil.getJsonAsInt(result,"status")!=0){
//										UIHelper.ToastMessage(PicCutActivity.this,"头像更改失败", Toast.LENGTH_SHORT);
//									}else{
//										UIHelper.ToastMessage(PicCutActivity.this,"头像更改成功", Toast.LENGTH_SHORT);
//										finish();
//									}
//								}
//								isSubmit = false;
//							}
//						}.execute();
//					}
//
//				}.execute();
//			}
			break;
		}
	}

	
	
}